/*
 * Copyright 2012 Faculty of Informatics - Masaryk University.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cz.muni.fi.pa165.creatures.rest.backend;

import cz.muni.fi.pa165.creatures.dto.WeaponDTO;
import cz.muni.fi.pa165.creatures.dto.mapping.WeaponMapping;
import cz.muni.fi.pa165.creatures.facades.EffectivityServiceFacade;
import cz.muni.fi.pa165.creatures.model.Weapon;
import cz.muni.fi.pa165.creatures.rest.backend.utils.WeaponDTOBuilder;
import cz.muni.fi.pa165.creatures.services.WeaponService;
import java.io.InputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * This class represents all CRUD like operations possible upon
 * {@link cz.muni.fi.pa165.creatures.model.Weapon}.
 *
 * @author xmiklos1
 */
@Component
@Path("weapon")
public class WeaponsResource implements EntityResource {

    @Autowired
    WeaponService weaponService;
    
    @Autowired
    EffectivityServiceFacade effectivityServiceFacade;
    
    @Autowired
    WeaponMapping weaponMapping;

    ////////////
    // CREATE
    ////////////

    @POST
    @Consumes(value = {MediaType.APPLICATION_XML})
    @Override
    public Response create(InputStream data) {
        try {
            WeaponDTO weaponDTO = new WeaponDTOBuilder().build(data);
            System.out.println(weaponDTO);
            if (weaponService.getByName(weaponDTO.getName()) == null) {
                Long id = weaponService.create(weaponDTO);
                return Response.created(URI.create("/" + id)).build();
            } else {
                return Response.status(Response.Status.FORBIDDEN).build();
            }
        } catch (Exception ex) {
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
        }
    }

    ////////////
    // DELETE
    ////////////

    @DELETE
    @Path("{id}")
    @Override
    public Response delete(@PathParam("id") String id) {
        try {
            Long idLong = Long.parseLong(id);
            WeaponDTO dto = weaponService.getById(idLong);
            if (dto != null) {
                effectivityServiceFacade.removeWeaponWithEffectivities(dto);
            } else {
                throw new IllegalArgumentException();
            }
            return Response.ok().build();
        } catch (NumberFormatException ex) {
            return Response.status(Response.Status.BAD_REQUEST).build();
        } catch (IllegalArgumentException ex) {
            return Response.status(Response.Status.NOT_FOUND).build();
        } catch (Exception ex) {
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
        }
    }

    ////////////
    // GET COUNT
    ////////////    
    
    @GET
    @Path("/count")
    @Produces({MediaType.TEXT_XML})
    @Override
    public Response getCount() {
        try {
            Long count = weaponService.getCount();
            String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
                    + "\n<count>" + count + "</count>";
            return Response.ok(xml).type(MediaType.APPLICATION_XML).build();
        } catch (Exception ex) {
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
        }
    }

    ////////////
    // GET BY ID
    ////////////
    
    @GET
    @Path("{id}")
    @Produces(value = {MediaType.APPLICATION_XML})
    @Override
    public Response getById(@PathParam("id") String id) {
        try {
            Weapon w = weaponMapping.DTOtoEntity(
                    weaponService.getById(Long.parseLong(id)));
            if (w == null) {
                throw new IllegalArgumentException();
            }
            return Response.ok(w).type(MediaType.APPLICATION_XML).build();
        } catch (NumberFormatException ex) {
            return Response.status(Response.Status.BAD_REQUEST).build();
        } catch (IllegalArgumentException ex) {
            return Response.status(Response.Status.NOT_FOUND).build();
        } catch (Exception ex) {
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
        }
    }

    ////////////
    // GET ALL
    ////////////

    @GET
    @Path("/all")
    @Produces({MediaType.APPLICATION_XML})
    @Override
    public Response getAll() {
        try {
            Collection<WeaponDTO> weaponsDTO = weaponService.getAll();

            List<Weapon> weapons = new ArrayList<Weapon>();

            for (WeaponDTO dto : weaponsDTO) {
                Weapon w = weaponMapping.DTOtoEntity(dto);
                weapons.add(w);
            }

            GenericEntity<Collection<Weapon>> ge =
                    new GenericEntity<Collection<Weapon>>(weapons) {
                    };
            return Response.ok().entity(ge).build();
        } catch (Exception ex) {
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
        }
    }

    ////////////
    // UPDATE
    ////////////

    @PUT
    @Consumes(value = {MediaType.APPLICATION_XML})
    @Override
    public Response update(InputStream data) {
        try {
            if (data == null) {
                return Response.status(Response.Status.BAD_REQUEST).build();
            }
            WeaponDTO dto = new WeaponDTOBuilder().build(data);
            if (weaponService.getById(Long.parseLong(dto.getId())) != null) {
                if (dto.getName() != null) {
                    WeaponDTO found = weaponService.getByName(dto.getName());
                    if (found != null && !found.getId().equals(dto.getId())) {
                        return Response.status(Response.Status.FORBIDDEN).build();
                    }
                }
            } else {
                return Response.status(Response.Status.NOT_FOUND).build();
            }
            System.out.println(dto);
            weaponService.update(dto);
            return Response.ok().build();
        } catch (NumberFormatException ex) {
            return Response.status(Response.Status.BAD_REQUEST).build();
        } catch (Exception ex) {
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
        }
    }
}
